package com.fm.common.net.baseCoroutine.exception

import androidx.lifecycle.LifecycleOwner
import com.ticket.rccl.net.baseCoroutine.listener.CoroutineLifecycleListener
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext

/**
 * @CreateData:     2020/12/22
 * @Author:         lyy
 * @Description:    类描述
 */

fun <T> GlobalScope.asyncWithLifecycleAsync(
    lifecycleOwner: LifecycleOwner,
    context: CoroutineContext = EmptyCoroutineContext,
    start: CoroutineStart = CoroutineStart.DEFAULT,
    block: suspend CoroutineScope.() -> T
): Deferred<T> {

    val deferred = GlobalScope.async(context, start) {

        block()
    }

    lifecycleOwner.lifecycle.addObserver(CoroutineLifecycleListener(deferred))

    return deferred
}

fun <T> GlobalScope.bindWithLifecycleAsync(
    lifecycleOwner: LifecycleOwner,
    block: GlobalScope.() -> Deferred<T>
): Deferred<T> {

    val deferred = block.invoke(this)

    lifecycleOwner.lifecycle.addObserver(CoroutineLifecycleListener(deferred))

    return deferred
}